package com.zzu.servlet;

import com.github.pagehelper.Page;
//import com.sun.webkit.dom.CounterImpl;
import com.zzu.model.Manager;
import com.zzu.model.PageUser;
import com.zzu.model.Student;
import com.zzu.model.Teacher;
import com.zzu.service.ManagerService;
import com.zzu.service.StudentService;
import com.zzu.service.TeacherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理登录请求
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private ManagerService managerService = new ManagerService();
    private TeacherService teacherService = new TeacherService();
    private StudentService studentService = new StudentService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //对用户登录进行校验
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");

        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        String href = "";
        if(managerService.findManager(id,password) != null){
            //管理员账号，将信息存入PageUser中
            System.out.println("管理员");
            Manager manager = managerService.findManager(id,password);
            PageUser pageUser = new PageUser(id,manager.getmName(),"管理员");
            request.getSession().setAttribute("pageUser",pageUser);
            out.print("1");//将1返回给前端
        }else if(teacherService.findTeacher(id,password) != null){
            //教师账号
            HttpSession session = request.getSession();
            session.setAttribute("teacherId",id);
            System.out.println("---------------------"+id);
            System.out.println("教师");
            Teacher teacher = teacherService.findTeacher(id,password);
            PageUser pageUser = new PageUser(id,teacher.gettName(),"教师");
            request.getSession().setAttribute("pageUser",pageUser);
            out.println("2");
        }else if(studentService.findStudent(id,password) != null){
            //读者账号
            HttpSession session = request.getSession();
            session.setAttribute("studentId",id);
            System.out.println("读者");
            Student student = studentService.findStudent(id,password);
            PageUser pageUser = new PageUser(id,student.getsName(),"学生");
            out.println("3");//将3返回给客户端
        }else{
            //提示用户登录失败，请重新登录
            System.out.println("用户登录失败");
            out.println("0");
        }
        out.flush();
        out.close();
    }
}
